package com.tencent.wepay.protocol.http;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tencent.wepay.protocol.IRequest;

public class HttpRequest implements IRequest{
	private static Logger logger=LoggerFactory.getLogger(HttpsRequest.class);
	//连接超时时间，默认10秒
    private static int socketTimeout = 10000;

    //传输超时时间，默认30秒
    private static int connectTimeout = 30000;
    
    private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
    
    private static CloseableHttpClient httpClient=HttpClients.custom().setMaxConnTotal(200).setMaxConnPerRoute(20).setRetryHandler(new DefaultHttpRequestRetryHandler()).build();
    
    private static HttpRequest request=null;
    private HttpRequest() {
		// TODO Auto-generated constructor stub
	}
    public static HttpRequest getInstance() {  
        if (request == null) {    
            synchronized (HttpRequest.class) {    
               if (request == null) {    
                  request = new HttpRequest();   
               }    
            }    
        }    
        return request;   
    }  
    @Override
	public String post(String url, String content) throws Exception {
    	return post(url, content, ContentType.create("text/xml",Consts.UTF_8));
    }

	@Override
	public String post(String url, String content, ContentType contentType) throws Exception {
		logger.debug("request content:"+content);
		HttpPost httpPost=new HttpPost(url);
		httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type",contentType.getMimeType());
		StringEntity postEntity=null;
		try {
			postEntity = new StringEntity(content,contentType.getCharset());
			httpPost.setEntity(postEntity);	
		    HttpResponse response = httpClient.execute(httpPost);
		    HttpEntity entity = response.getEntity();
		    return EntityUtils.toString(entity,contentType.getCharset());
		} catch (Exception e) {
			logger.error(url+",send request error",e);
			throw e;
		}finally{
			httpPost.abort();
		}
	}

	@Override
	public String get() {
		// TODO Auto-generated method stub
		return null;
	}

}
